<?php

class UsersController extends AppController {
  var $paginate = array(
    'Point' => array(
      'order' => 'Point.created DESC',
      'limit' => 10,
    ),
    'User' => array(
      'order' => 'User.point_count DESC',
    ),
  );
  
  function login($code = NULL) {
    
    $this->Browniepoints->css('openid');
    $this->Browniepoints->js('jquery-1.3.2.min');
    $this->Browniepoints->js('jquery.openid');
    $this->Browniepoints->js('inline', 'openid_js');
    // $this->Browniepoints->js('inline', 'twitter_js');

    if ($this->data) {
      if (empty($this->data['LocalAccount']['password']) || $this->data['op'] == __('Kennwort vergessen', /*return*/TRUE)) {
        $this->recover();
      }
    }
    else
    if ($code) {
      $this->data = $this->LocalAccount->find('first', array(
        'conditions' => array('code' => $code),
        'recursive' => 1,
      ));
      if ($this->data) {
        $this->LocalAccount->id = $this->data['LocalAccount']['id'];
        $this->LocalAccount->saveField('code', NULL);
      }
    }    
    
    if ($this->data) {
      $this->Session->write('auth_component', 'LocalAuth');
      if ($destination = $this->LocalAuth->login($this->data)) {
        $this->setSuccess('Du bist jetzt angemeldet.', $destination);
      }
      else {
        $this->setError('Die Anmeldung hat nicht funktioniert.', $this->here);
      }
    }
  }

  function recover() {
    if ($this->account) {
      $this->setError('Du bist bereits angemeldet.', array('action' => 'view', $this->User->user_id($this->account)));
    }
    
    if (!$this->data) {
      $this->setError('Bitte gib deinen Nutzernamen an.', array('action' => 'login'));
    }
      
    $account = $this->LocalAccount->find('first', array(
      'conditions' => array('username' => $this->data['LocalAccount']['username']),
      'fields' => array('LocalAccount.id', 'LocalAccount.code', 'User.email')
    ));
    if (!$account) {
      $this->setError('Diesen Nutzernamen gibt es nicht.', array('action' => 'login'));
    }

    $unique = FALSE;
    $until = time() + 86400; // 1d
    while (!$unique) {
      $code = base_convert(rand(), 10, 36);
      $this->LocalAccount->set('id', $account['LocalAccount']['id']);
      $unique = $this->LocalAccount->save(array('code' => $code, 'code_until' => $until));
    }

    App::import('Component', 'Email');

    $link = 'http://' . $_SERVER['HTTP_HOST'] . '/u/' . $code;

    $email = new EmailComponent;
    $email->to = $account['User']['email'];
    $email->from = 'Browniepoints <info@browniepoints.de>';
    $email->subject = 'Kennwort vergessen?';
    $email->send("Hallo,

um dich anzumelden, klicke auf den folgenden Link:

{$link}

Dein Browniepunkt-Depot.");

    $this->setSuccess('Du hast soeben eine E-Mail mit einen Link erhalten.', array('action' => 'login'));
  }

  function logout() {
    $this->Auth->logout();
    $this->setSuccess('Du bist jetzt abgemeldet.', array('controller' => 'points', 'action' => 'home'));
  }

  function register() {
    if ($this->data) {
      if ($this->data['LocalAccount']['password'] != $this->Auth->password($this->data['LocalAccount']['password_confirm'])) {
        $this->Session->setFlash('Die Kennworte stimmen nicht überein', 'default', array(), 'auth');
      }
      else { 
        if ($account = $this->Auth->user()) {
          // logged in. Attach new account to existing user
          $user_id = $this->User->user_id($user_id);
        }
        else {
 
          $errors = array(); // collect both User and LocalAccount errors here

          if (isset($data['User']['name'])) {
            $this->User->set($this->data);
            if (!$this->User->validates()) {
               $errors += $this->User->invalidFields();
            }
          }

          $this->LocalAccount->set($this->data);
          if (!$this->User->validates()) {
             $errors += $this->User->invalidFields();
          }

          if ($errors) {
            $user_id = 0;
            $this->Session->setFlash('Dein Konto konnte nicht angelegt werden: ' 
              . join("<br/>", $errors), 'default', array(), 'auth');
          }
          else {
            $this->User->create();
            $this->User->save($this->data, /*validate*/FALSE); // has been validated above
            $user_id = $this->User->getInsertID();
          }
        }

        if ($user_id) {
          $this->LocalAccount->create();
          $this->data['LocalAccount']['user_id'] = $user_id;
          if ($this->LocalAccount->save($this->data)) {
            $this->Session->setFlash('Dein neues Konto wurde angelegt.');
            $this->Auth->login();
            $this->redirect(array('controller' => 'points', 'action' => 'home'));
          }
          else {
            $this->Session->setFlash('Dein Konto konnte nicht angelegt werden: '
              . join("<br/>", $this->LocalAccount->invalidFields()), 'default', array(), 'auth');
          }
        }
      }
    }
  }
  
  function view($id = NULL, $tab = 'points-in') { 
    if ($id == NULL) {
      if (!$this->account) {
        $this->setError('Bitte melde dich an.', 
          array('controller' => 'users', 'action' => 'login'));
      }
      $id = $this->account['User']['id'];
    }

    // fetch points separately
    $this->User->unbindModel(array('hasMany' => array('Point')));

    $this->set('user', $this->data = $this->User->find('first', array(
      'conditions' => array('User.id' => $id),
    )));

    $is_own = FALSE;
    $aspect = 'points'; 
    $direction = 'in';

    if ($this->account) {
      $this->set('account_user_id', $user_id = $this->account['User']['id']);
      if ($user_id == $id) { 
        $is_own = TRUE;
        @list($aspect, $direction) = split('-', $tab);
        
        $this->set('tabs', array(
          'Erhalten' => array('/users/view/\d+', 'controller' => 'users', 'action' => 'view', $this->data['User']['id']),
          'Vergeben' => array('/users/view/\d+/points-out', 'controller' => 'users', 'action' => 'view', $this->data['User']['id'], 'points-out'),
          'Konten' => array('/users/view/\d+/accounts', 'controller' => 'users', 'action' => 'view', $this->data['User']['id'], 'accounts'),
        ));
      }
    }

    $this->set('is_own', $is_own);
    $this->set('aspect', $aspect);
    $this->set('direction', $direction);
    
    if ($aspect == 'points') {
      $field = $direction == 'in' ? 'Point.user_id' : 'Point.sender_id';
      $conditions = array($field => $id);
      if (!$is_own) {
        // $conditions['visible'] = 1;
      }
      $this->set('points', $this->paginate('Point', $conditions));
    }
    else {
      $this->User->unbindModel(array('hasMany' => array('LocalAccount')));
      $this->User->unbindModel(array('hasMany' => array('TwitterAccount')));
      $this->User->unbindModel(array('hasMany' => array('OpenidAccount')));      
    }

    $this->setCaptcha();
  }

  function index() {
    $this->set('users', $this->paginate('User', array('name !=' => 'Browniepunkt')));
  }

  function edit($id) {
    $account = $this->Auth->user(); 
    
    if (!$account) {
      $this->setError('Bitte melde dich an.', 
        array('controller' => 'users', 'action' => 'login'));
    }
    $user_id = $this->User->user_id($account);
    if ($id != $user_id) {
      $this->setError('Du darfst dieses Profil nicht bearbeiten.', 
        array('controller' => 'users', 'action' => 'view', $id));
    }

    if ($this->data) {
      $this->User->set('id', $id);
      if ($this->User->save($this->data)) {
        $this->setSuccess('Die Änderungen wurden gespeichert.', 
          array('controller' => 'users', 'action' => 'view', $id));
      }
      else {
        $this->setError(join('<br />', $this->User->validationErrors), 
          array('controller' => 'users', 'action' => 'view', $id));        
      }
    }
  }

  function badge() {

  Configure::write('debug', 2);
    // e28e2b8b39b8c503f72aa24ae328ede0
    header('Content-type: image/png');
    header('Expires: ' . date('r', strtotime('last year')));
    header('Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
    header('Pragma: no-cache');
    $this->autoRender = FALSE;

    $point_count = $this->User->field('point_count', array('email_md5' => $this->params['hash']));
    if ($point_count === FALSE) {
      $file = $_SERVER['DOCUMENT_ROOT'] . '/img/bp/brownie_100x100.png';
    }
    else {
      // should not be necessary
      $point_count = intval($point_count);
      $file = "{$_SERVER['DOCUMENT_ROOT']}/img/badge/btn-{$point_count}.png";
      if (!file_exists($file)) {
        if ($point_count < 10) {
          $size = 40;
        }
        else
        if ($point_count < 100) {
          $size = 34;
        }
        else
        if ($point_count < 1000) {
          $size = 26;
        }
        else {
          $size = 16;
        }

        $cmd = "convert {$_SERVER['DOCUMENT_ROOT']}/img/bp/brownie_100x100.png -font {$_SERVER['DOCUMENT_ROOT']}/img/verdanab.ttf -pointsize {$size} -gravity Center -fill white -annotate +0-2 '{$point_count}' {$file}";
        system($cmd);
      }
    };
    readfile($file);
  }
}
